const utils = require("../../../utils/util");
const cloud = require("../../../utils/api");
const app = getApp();
// pages/blogs/classify/classify.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    hide: app.globalData.hide,
    blogsList: [],
    searchBlogsList: [],
    search: false,
    scrollTop: 0,
    page: 0,
    moreList: true,
    type: "",
    themeType: app.globalData.themeType,
  },

  getBlogsList(type, skip) {
    const that = this;
    cloud.cloudGet("blogs", { classify: type }, true, 20, skip).then((res) => {
      if (res.length == 0) {
        that.setData({
          moreList: false,
          page: 0,
        });
        wx.showToast({
          title: "没有更多了",
          icon: "none",
        });
      }
      let { blogsList } = that.data;
      blogsList = blogsList.concat(utils.reSortArr(res));
      that.setData(
        {
          blogsList,
        },
        () => {
          wx.hideLoading();
        }
      );
    });
  },

  goDetail(e) {
    let { item } = e.currentTarget.dataset;
    wx.navigateTo({
      url: "/pages/blogs/detail/detail?id=" + item._id + "&title=" + item.title + "&type=" + (item.type ? item.type : "markdown"),
    });
  },

  onSearch(e) {
    const { list, search } = e.detail;
    this.setData({
      searchBlogsList: list,
      search,
    });
  },

  scrollTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300,
    });
  },
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop,
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { type } = options;
    const hide = app.globalData.hide;
    this.setData({ hide, type });
    if (hide) return;
    wx.setNavigationBarTitle({
      title: type,
    });
    this.getBlogsList(type);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      themeType: app.globalData.themeType,
    });

    const themeType = wx.getStorageSync("themeType");
    if (themeType == "dark") {
      wx.setNavigationBarColor({
        backgroundColor: "#000000",
        frontColor: "#ffffff",
      });
    } else {
      wx.setNavigationBarColor({
        backgroundColor: "#ffffff",
        frontColor: "#000000",
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    const that = this;
    let { page, moreList, type } = that.data;
    if (moreList == false) return;
    page += 20;
    that.setData({
      page,
    });
    this.getBlogsList(type, page);
  },
});
